import XLSX from "xlsx";
import axios from "axios";
import csv2json from "csvtojson";

import { check, Config } from "./typechecker";
import { computed, Ref, SetupContext } from "@vue/composition-api";

export async function xlsxParser(file: string) {
	const { data } = await axios.get(file, {
		responseType: "arraybuffer",
	});
	const workbook = XLSX.read(new Uint8Array(data), { type: "array" });

	return XLSX.utils.sheet_to_json(workbook.Sheets["Sheet1"]);
}

export function getAllData(ctx: SetupContext, force: boolean = false) {
	const state = computed(() => ctx.root.$store.state);
	const config: Ref<Config[]> = computed(() => state.value.config);

	if (config.value.length <= Object.keys(state.value.data).length && !force) {
		return;
	}

	config.value.forEach(async (item, index) => {
		if (typeof item.data !== "string" && check.isJSON(item.data)) {
			state.value.data = {
				...state.value.data,
				[String(index)]: [item.data[0], ...(item.data as any[])],
			};
		} else {
			let data: any[] = [];

			if (item.data.endsWith("xlsx") || item.data.endsWith("xls")) {
				const xlsxData = await xlsxParser(item.data);
				const xlsxKeys = Object.keys(xlsxData[0] as { [p: string]: string });
				const headItem = Object.fromEntries(
					Object.entries(xlsxKeys).map(([_, v]) => [v, v])
				);
				data = [headItem, ...xlsxData];
			} else {
				const res = await axios.get(item.data);
				data = (
					await csv2json().fromString(
						item.config.map(({ label }) => label).join(",") + "\n" + res.data
					)
				).filter((e) => !check.isObjectFullOfNull(e));
			}

			state.value.data = {
				...state.value.data,
				[String(index)]: data,
			};
		}
	});
}

export function ajaxDownloadFile(url: string, name?: string) {
	axios
		.get(url, {
			responseType: "blob",
		})
		.then((res) => {
			let link = document.createElement("a");
			link.href = window.URL.createObjectURL(new Blob([res.data]));
			link.setAttribute(
				"download",
				name || url.slice(url.lastIndexOf("/") + 1)
			);
			link.click();
		});
}
